package com.sky.base.security.service;

import com.sky.base.constant.UserStatus;
import com.sky.base.security.pojo.LoginUser;
import com.sky.exception.BaseException;
import com.sky.model.SysUser;
import com.sky.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/8/9
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username);
        // 判断登录的用户是否有效
        if (Objects.isNull(user))
        {
            throw new BaseException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            throw new BaseException("对不起，您的账号：" + username + " 已删除");
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user);
    }
}
